<?php
namespace Application\Html\Controller;

class Order extends Base
{

    public function init()
    {
        $this->setDir('order');
        $this->setTemplate('downloadList', 'downloadList');
    }

    public function indexAction()
    {
        $data = $this->getRequestData();
        $device = DEVICE_WEIXIN_SP;
        if(setAndNotEmpty($data, 'device')){
            $device = $data['device'];
        }
        $serviceUser = $this->get(SERVICE_USER);
        $userId = $serviceUser->checkToken($data, $device);
        if(!$userId){
            $this->sendFail('TOKEN_ERROR', '', __LINE__);
            return false;
        }
        $serviceOrder = $this->get(SERVICE_ORDER);
        $send = [];
        $send['count'] = $serviceOrder->getCount($userId);
        $this->setFile($this->getTemplateIndex());
        $this->setData($send);
        $this->show();
    }

    public function downloadListAction()
    {
        $get = $this->getQueryData();
        $send = [];
        $send['id'] = (int)$get['id'];
        $send['list'] = getDrycmsVipVersionList();
        $this->setFile($this->getTemplate('downloadList'));
        $this->setData($send);
        $this->show();
    }

    public function downloadAction()
    {
        $data = $this->getRequestData();
        if(notSetOrEmpty($data, 'id') || notSetOrEmpty($data, 'version') || notSetOrEmpty($data, 'device') || notSetOrEmpty($data, 'token')){
            $this->sendFail('PARAMETER_ERROR', '', __LINE__);
            return false;
        }
        $id = (int)$data['id'];
        $version = $data['version'];
        $device = $data['device'];

        $serviceUser = $this->get(SERVICE_USER);
        $userId = $serviceUser->checkToken($data, $device);
        if(!$userId){
            $this->sendFail('TOKEN_ERROR', '', __LINE__);
            return false;
        }
        $serviceOrder = $this->get(SERVICE_ORDER);
        $order = $serviceOrder->one($data['id']);
        if(empty($order)){
            $this->sendFail('PARAMETER_ERROR', '', __LINE__);
            return false;
        }
        $product = json_decode($order->dry_product_raw, false);
        $bool = $serviceOrder->canDownload($userId, $order, $product);
        if($bool == '0'){
            $this->sendFail('TOKEN_ERROR', '', __LINE__);
            return false;
        }
        $mainProduct = $product->dry_main_product;
        $url = getOssDomain() . "/download/{$mainProduct}/{$version}";
        $content = file_get_contents($url);
        $this->downloadZip($version);
        $this->response->end($content);
    }

}